package com.yl.chainStore.services.impl

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper
import com.yl.chainStore.common.enums.TypeEnum
import com.yl.chainStore.entity.system.SysNumGenerator
import com.yl.chainStore.entity.system.SysNumGeneratorPrefixSetting
import com.yl.chainStore.mapper.system.SysNumGeneratorMapper
import com.yl.chainStore.mapper.system.SysNumGeneratorPrefixSettingMapper
import com.yl.chainStore.pojo.vo.system.SysNumGeneratorSelectVo
import com.yl.chainStore.services.ISysNumGeneratorService
import com.yl.chainStore.services.ITechnologyProcessingService
import com.yl.common.ErrorCode
import com.yl.common.control.ResponseBody
import com.yl.common.control.returnError
import com.yl.common.control.returnSuccess
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Service
import java.sql.Wrapper
import java.text.SimpleDateFormat
import java.util.*

@Service
class SysNumGeneratorServiceImpl(
	private val sysNumGeneratorMapper: SysNumGeneratorMapper,
	private val sysNumGeneratorPrefixSettingMapper: SysNumGeneratorPrefixSettingMapper
) : ISysNumGeneratorService {
	companion object {
		private val log = LoggerFactory.getLogger(ISysNumGeneratorService::class.java)
	}

	// 格式化的时间字符串
	private val sdf = SimpleDateFormat("yyMMdd")


	override fun getNewNum(companyId: Long, type: TypeEnum, subCompanyId: Long?): SysNumGenerator {
		log.info("号码管理 ==> 号码生成: companyId:{},type:{},subCompanyId:{}", companyId, type, subCompanyId)
		val prefix = getNumPrefixSetting(companyId, type, subCompanyId)?.prefix ?: ""

		//先获取当日未使用的第一张
		val selectVo = SysNumGeneratorSelectVo(
			companyId = companyId,
			subCompanyId = subCompanyId,
			type = type,
			day = Date(),
			useInfo = 0,
			orderStr = "create_time"
		)
		val one = sysNumGeneratorMapper.getOne(selectVo)
		if (one != null) {
			return one
		}
		//当日已使用的最后一张
		selectVo.useInfo = 1
		selectVo.orderStr = null
		val num = sysNumGeneratorMapper.getOne(selectVo)
		val countNum = if (num == null) {
			1
		} else {
			num.useNum + 1
		}
		val useNum = generateOrder(countNum)
		val resNum = SysNumGenerator(
			id = 0L,
			companyId = companyId,
			subCompanyId = subCompanyId,
			type = type,
			useNum = countNum,
			numShow = prefix + useNum
		)
		sysNumGeneratorMapper.insert(resNum)
		return resNum
	}



	override fun createPayLogNum(companyId: Long, type: TypeEnum, subCompanyId: Long?): SysNumGenerator {
		log.info("号码管理 ==> 号码生成: companyId:{},type:{},subCompanyId:{}", companyId, type, subCompanyId)
		//先获取当日未使用的第一张
		val selectVo = SysNumGeneratorSelectVo(
			companyId = companyId,
			subCompanyId = subCompanyId,
			type = type,
			useInfo = 1,
		)
		//当日已使用的最后一张
		val num = sysNumGeneratorMapper.getOne(selectVo)
		val countNum = if (num == null) {
			1
		} else {
			num.useNum + 1
		}
		val useNum = generatePayLogNum(countNum)
		val resNum = SysNumGenerator(
			id = 0L,
			companyId = companyId,
			subCompanyId = subCompanyId,
			type = type,
			useNum = countNum,
			numShow =  useNum,
			useInfo = 1
		)
		sysNumGeneratorMapper.insert(resNum)
		return resNum

	}

	override fun createPayLogNumByDay(companyId: Long, type: TypeEnum, subCompanyId: Long?,day:Date): SysNumGenerator {
		log.info("号码管理 ==> 号码生成: companyId:{},type:{},subCompanyId:{}", companyId, type, subCompanyId)
		//先获取当日未使用的第一张
		val selectVo = SysNumGeneratorSelectVo(
			companyId = companyId,
			subCompanyId = subCompanyId,
			type = type,
			useInfo = 1,
			day = day
		)
		//当日已使用的最后一张
		val num = sysNumGeneratorMapper.getOne(selectVo)
		val countNum = if (num == null) {
			1
		} else {
			num.useNum + 1
		}

		val useNum = generatePayLogNum(countNum)
		val resNum = SysNumGenerator(
			id = 0L,
			companyId = companyId,
			subCompanyId = subCompanyId,
			type = type,
			useNum = countNum,
			numShow =  useNum,
			useInfo = 1,
			createTime = day
		)
		sysNumGeneratorMapper.insert(resNum)
		return resNum

	}




	override fun getSysNumIsUse(companyId: Long, type: TypeEnum, subCompanyId: Long?, numShow: String): Boolean {
		log.info(
			"号码管理 ==> 查询是否使用: companyId:{},type:{},subCompanyId:{},numShow:{}",
			companyId,
			type,
			subCompanyId,
			numShow
		)
		val queryWrapper = QueryWrapper<SysNumGenerator>()
		queryWrapper.eq("company_id", companyId)
			.eq("type", type)
			.eq("num_show", numShow)
			.eq("use_info", 1)
		if (subCompanyId != null) {
			queryWrapper.eq("sub_company_id", subCompanyId)
		}
		return sysNumGeneratorMapper.selectCount(queryWrapper) != 0
	}

	override fun useSysNum(companyId: Long, type: TypeEnum, subCompanyId: Long?, numShow: String): ResponseBody {
		log.info("号码管理 ==> 使用号码: companyId:{},type:{},subCompanyId:{}，numShow:{}", companyId, type, subCompanyId,numShow)
		val queryWrapper = QueryWrapper<SysNumGenerator>()
		queryWrapper.eq("company_id", companyId)
			.eq("type", type)
			.eq("num_show", numShow)
		if (subCompanyId != null) {
			queryWrapper.eq("sub_company_id", subCompanyId)
		}
		val list = sysNumGeneratorMapper.selectList(queryWrapper)
		if (list.isEmpty()) {
			return returnSuccess()
		}
		// TODO: 2021/11/17  暂时默认只能生成一个
		val num = list[0]
		if (num.useInfo == 1) {
			return returnError(ErrorCode.OPERATION_DATA_ERROR, "号码已被使用")
		}
		num.useInfo = 1
		sysNumGeneratorMapper.updateById(num)
		return returnSuccess()
	}

	override fun setNumSetting(setting: SysNumGeneratorPrefixSetting): ResponseBody {
		log.info("号码管理 ==> 设置生成前缀: setting:{},", setting)

		val wrapper = QueryWrapper<SysNumGeneratorPrefixSetting>()
		wrapper.eq("company_id", setting.companyId)
			.eq("type", setting.type)
		if (setting.subCompanyId != null) {
			wrapper.eq("sub_company_id", setting.subCompanyId)
		}

		val selectList = sysNumGeneratorPrefixSettingMapper.selectList(wrapper)
		if (selectList.isEmpty()) {
			sysNumGeneratorPrefixSettingMapper.insert(setting)
		} else {
			val resSetting = selectList[0]
			resSetting.prefix = setting.prefix
			sysNumGeneratorPrefixSettingMapper.updateById(resSetting)
		}
		return returnSuccess()
	}

	override fun getNumPrefixSetting(
		companyId: Long,
		type: TypeEnum,
		subCompanyId: Long?
	): SysNumGeneratorPrefixSetting? {
		log.info("号码管理 ==> 使用号码: companyId:{},type:{},subCompanyId:{}", companyId, type, subCompanyId)

		val wrapper = QueryWrapper<SysNumGeneratorPrefixSetting>()
		wrapper.eq("company_id", companyId)
			.eq("type", type)
		if (subCompanyId != null) {
			wrapper.eq("sub_company_id", subCompanyId)
		}
		val selectList = sysNumGeneratorPrefixSettingMapper.selectList(wrapper)
		return if (selectList.isEmpty()) {
			null
		} else {
			selectList[0]
		}
	}

	private fun generateOrder(countNum: Long): Long {
		val dataStr = sdf.format(Date())

		val countInteger = 3 - countNum.toString().length // 算补位
		var bu = "" // 补字符串
		if (countInteger > 0) {
			for (i in 0 until countInteger) {
				bu += "0"
			}
		}
		bu += countNum.toString()

		return (dataStr + bu).toLong()
	}

	private fun generatePayLogNum(countNum: Long): String {

		val countInteger = 7 - countNum.toString().length // 算补位
		var bu = "" // 补字符串
		if (countInteger > 0) {
			for (i in 0 until countInteger) {
				bu += "0"
			}
		}
		bu += countNum.toString()

		return  bu
	}
}
